import { NextFunction, Request, Response } from 'express'
import * as Joi from 'joi'
import { AppError } from '../utils/AppError'

const schemas = {
  createOrder: Joi.object({
    amount: Joi.number().min(1).max(50000).required(),
    payType: Joi.string().valid('alipay', 'wechat', 'qq').required(),
  }),

  phoneLogin: Joi.object({
    phone: Joi.string()
      .pattern(/^1[3-9]\d{9}$/)
      .required(),
    code: Joi.string().length(6).required(),
  }),
}

export const validate = (schemaName: keyof typeof schemas) => {
  return (req: Request, _res: Response, next: NextFunction) => {
    const schema = schemas[schemaName]
    const { error } = schema.validate(req.body)

    if (error) {
      throw new AppError(400, error.details[0].message)
    }

    next()
  }
}
